package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.aspectj.lang.reflect.MethodSignature;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;


@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointcut() {}

    @Before("autoFillPointcut()")
    public void autoFill(JoinPoint joinPoint){

        //获取注解内容INSERT|UPDATE
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill=methodSignature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = autoFill.value();

        //获取相关数据
        Object[] args = joinPoint.getArgs();
        if(args==null || args.length==0){
            return;
        }
        Object arg = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long userId = BaseContext.getCurrentId();

        //增强
        if (OperationType.INSERT.equals(value)) {
            try {
                arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class).invoke(arg, now);
                arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(arg, now);
                arg.getClass().getDeclaredMethod("setCreateUser", Long.class).invoke(arg, userId);
                arg.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(arg, userId);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }else if(OperationType.UPDATE.equals(value)){
            try {
                arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(arg, now);
                arg.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(arg, userId);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }

    }



}
